from datetime import datetime
import json
from src.database import db


class Course(db.Model):
    """课程模型"""
    __tablename__ = 'courses'

    id = db.Column(db.Integer, primary_key=True)
    code = db.Column(db.String(20), unique=True, nullable=False, index=True)  # 课程代码
    name = db.Column(db.String(128), nullable=False, index=True)  # 课程名称
    teacher = db.Column(db.String(64), nullable=False)  # 教师姓名
    description = db.Column(db.Text, nullable=True)  # 课程描述
    credits = db.Column(db.Float, nullable=False)  # 学分
    capacity = db.Column(db.Integer, default=100)  # 课程容量
    selected_count = db.Column(db.Integer, default=0)  # 已选人数

    # 存储为JSON字符串的字段
    grade_req = db.Column(db.String(256), default='[]')  # 年级要求，如[1,2]表示大一大二可选
    major_req = db.Column(db.String(512), default='[]')  # 专业要求，如["计算机科学","软件工程"]
    schedule = db.Column(db.JSON)  # 课程时间表，如[{"day":1,"start":1,"end":2}]

    # 评分
    score_teaching = db.Column(db.Float, default=0)  # 教学评分
    score_difficulty = db.Column(db.Float, default=0)  # 难度评分
    score_workload = db.Column(db.Float, default=0)  # 作业量评分

    semester = db.Column(db.String(20), nullable=False)  # 学期，如"2023-2024-1"
    is_active = db.Column(db.Boolean, default=True)  # 是否激活
    created_at = db.Column(db.DateTime, default=datetime.utcnow)
    updated_at = db.Column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)

    # 关系
    selections = db.relationship('Selection', backref='course', lazy='dynamic', cascade='all, delete-orphan')
    reviews = db.relationship('CourseReview', backref='course', lazy='dynamic', cascade='all, delete-orphan')

    @property
    def grade_req_list(self):
        """获取年级要求列表"""
        return json.loads(self.grade_req)

    @grade_req_list.setter
    def grade_req_list(self, value):
        """设置年级要求列表"""
        self.grade_req = json.dumps(value)

    @property
    def major_req_list(self):
        """获取专业要求列表"""
        return json.loads(self.major_req)

    @major_req_list.setter
    def major_req_list(self, value):
        """设置专业要求列表"""
        self.major_req = json.dumps(value)

    @property
    def schedule_list(self):
        """获取课程时间表列表"""
        return json.loads(self.schedule)

    @schedule_list.setter
    def schedule_list(self, value):
        """设置课程时间表列表"""
        self.schedule = json.dumps(value)

    def to_dict(self):
        """将课程对象转换为字典"""
        return {
            'id': self.id,
            'code': self.code,
            'name': self.name,
            'teacher': self.teacher,
            'description': self.description,
            'credits': self.credits,
            'capacity': self.capacity,
            'selected_count': self.selected_count,
            'grade_req': self.grade_req_list,
            'major_req': self.major_req_list,
            'schedule': self.schedule_list,
            'semester': self.semester,
            'score_teaching': self.score_teaching,
            'score_difficulty': self.score_difficulty,
            'score_workload': self.score_workload,
            'is_active': self.is_active,
            'created_at': self.created_at.isoformat() if self.created_at else None,
            'updated_at': self.updated_at.isoformat() if self.updated_at else None
        }

    def __repr__(self):
        return f'<Course {self.code}: {self.name}>'

class CourseSelection(db.Model):
    __tablename__ = 'course_selections'
    
    id = db.Column(db.Integer, primary_key=True)
    user_id = db.Column(db.Integer, db.ForeignKey('users.id'), nullable=False)
    course_id = db.Column(db.Integer, db.ForeignKey('courses.id'), nullable=False)
    
class CourseRating(db.Model):
    __tablename__ = 'course_ratings'
    
    id = db.Column(db.Integer, primary_key=True)
    user_id = db.Column(db.Integer, db.ForeignKey('users.id'), nullable=False)
    course_id = db.Column(db.Integer, db.ForeignKey('courses.id'), nullable=False)
    rating_type = db.Column(db.String(32))  # teaching, difficulty, workload
    score = db.Column(db.Integer)
    comment = db.Column(db.Text)
